#!/usr/bin/perl
# being parsing batting stats
$cutoff =2000;

$filetoParse = "Batting.csv";

@headings = ("playerid","yearid","stint","teamid","lgid","g","g_batting","ab","r","h","2b","3b","hr","rbi","sb","cs","bb","so","ibb","hbp","sh","sf","gidp","g_old");


%statsbyYear;

$filter = 0;

open (FILE, $filetoParse);
while (<FILE>) {
    chomp;
    
    $count = 0;
    @line = split(",");

    #print "$line[1] is the year\n";
    $tempYear = $line[1];
    $tempPlayer = $line[0];
    
    if($line[1] >= $cutoff )
    {
	foreach $stat(@line) {
	    
	    #save players ID                                                                                                                                  
	    if($count == 0)
	    {
		$id = $stat;
	    }
	    
	    #clear new line off input                                                                                                                         
	    if($count == scalar(@headings)-1 )
	    {
		chop($stat);
	    }
	    
	    if($count > 1){
		
		if ($stat =~ /"/)
		{
		    #already formatted correctly
		}
		else
		{
		    #add quotes
		    $stat = "\"" . $stat . "\""; 
		}
		
		$statsByYear{$headings[$count]}{$tempYear} = $statsByYear{$headings[$count]}{$tempYear} . "{\"playerid\":$tempPlayer, \"$headings[$count]\":$stat},";
		
		#print "stored: stat($headings[$count]) year($tempYear) =  $statsByYear{$headings[$count]}{$tempYear} \n";
		
		
	    }
	    
	    $count++;
	}
    }
    else
    {
	#print "$line[0] outside of date range\n";
	
    }
    
}



for $stat (sort keys %statsByYear)
{


    for $year (sort keys %{ $statsByYear{$stat} })
    {
	chop($statsByYear{$stat}{$year});
	#print "var $year-stat = [$statsByYear{$stat}{$year}] \n\n";

	$fileName = ">batting/" . $stat . "/" . $year .".js";

	#print "filename: $fileName\n";

	open (MYFILE,$fileName);  
	print MYFILE "var $year-$stat = [$statsByYear{$stat}{$year}]; \n\n";
	close (MYFILE);

	
	

	#<>;
	
    }
}


#print MYFILE "]; ";
#close(MYFILE);



exit;
